<template>
  <div class="app-container">
    <div class="app-card">
      <!-- 搜索和工具栏 -->
      <div class="table-toolbar">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-form-item label="路线名称">
            <el-input v-model="queryParams.name" placeholder="请输入路线名称" clearable size="small" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
              <el-option :value="1" label="启用" />
              <el-option :value="0" label="禁用" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        
        <div>
          <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
        </div>
      </div>
      
      <!-- 表格 -->
      <el-table v-loading="loading" :data="routeList" border>
        <el-table-column type="index" label="#" width="50" align="center" />
        <el-table-column prop="name" label="路线名称" min-width="150" />
        <el-table-column prop="description" label="路线描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          :current-page="queryParams.current"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="路线名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入路线名称" />
        </el-form-item>
        <el-form-item label="路线描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入路线描述" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="配送团长" prop="items">
          <div class="route-items">
            <div v-if="form.items.length === 0" class="empty-tip">
              请添加配送团长
            </div>
            <el-card v-for="(item, index) in form.items" :key="index" class="route-item">
              <div slot="header" class="route-item-header">
                <span>配送点 {{ index + 1 }}</span>
                <el-button type="text" icon="el-icon-delete" @click="removeRouteItem(index)">删除</el-button>
              </div>
              <el-form-item :prop="'items.' + index + '.leaderId'" :rules="{ required: true, message: '请选择团长', trigger: 'change' }">
                <el-select v-model="item.leaderId" placeholder="请选择团长" style="width: 100%">
                  <el-option 
                    v-for="leader in availableLeaders" 
                    :key="leader.id" 
                    :label="leader.name + ' - ' + leader.address" 
                    :value="leader.id"
                    :disabled="isLeaderSelected(leader.id, index)"
                  />
                </el-select>
              </el-form-item>
              <div class="route-item-info" v-if="item.leaderId">
                <div class="leader-info">
                  <span class="label">团长:</span>
                  <span>{{ getLeaderName(item.leaderId) }}</span>
                </div>
                <div class="leader-info">
                  <span class="label">地址:</span>
                  <span>{{ getLeaderAddress(item.leaderId) }}</span>
                </div>
              </div>
            </el-card>
            <div class="add-item">
              <el-button type="dashed" icon="el-icon-plus" @click="addRouteItem">添加配送点</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 详情对话框 -->
    <el-dialog title="配送路线详情" :visible.sync="detailVisible" width="700px" append-to-body>
      <div v-loading="detailLoading">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="路线名称">{{ routeDetail.route?.name }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="routeDetail.route?.status === 1 ? 'success' : 'info'">
              {{ routeDetail.route?.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ routeDetail.route?.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ routeDetail.route?.updateTime }}</el-descriptions-item>
          <el-descriptions-item label="路线描述" :span="2">{{ routeDetail.route?.description }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="route-map" v-if="routeDetail.items && routeDetail.items.length > 0">
          <div class="route-map-title">配送路线图</div>
          <div class="route-map-content">
            <div v-for="(item, index) in routeDetail.items" :key="index" class="route-point">
              <div class="route-step">
                <div class="point-number">{{ index + 1 }}</div>
                <div class="point-line" v-if="index < routeDetail.items.length - 1"></div>
              </div>
              <div class="point-card">
                <div class="point-header">{{ item.leaderName }}</div>
                <div class="point-body">
                  <div class="point-item">
                    <i class="el-icon-phone"></i>
                    <span>{{ item.leaderPhone }}</span>
                  </div>
                  <div class="point-item">
                    <i class="el-icon-location"></i>
                    <span>{{ item.leaderAddress }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listDeliveryRoutes, 
  getDeliveryRoute, 
  addDeliveryRoute, 
  updateDeliveryRoute, 
  deleteDeliveryRoute, 
  changeDeliveryRouteStatus, 
  getAvailableLeaders 
} from '@/api/delivery-route'

export default {
  name: 'DeliveryRoute',
  data() {
    return {
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: '',
        status: ''
      },
      // 总记录数
      total: 0,
      // 路线列表
      routeList: [],
      // 加载状态
      loading: false,
      // 对话框标题
      dialogTitle: '',
      // 对话框显示状态
      dialogVisible: false,
      // 表单对象
      form: {
        id: undefined,
        name: '',
        description: '',
        status: 1,
        items: []
      },
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '请输入路线名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        items: [
          { required: true, type: 'array', message: '请至少添加一个配送点', trigger: 'change' }
        ]
      },
      // 可用的团长列表
      availableLeaders: [],
      // 详情对话框显示状态
      detailVisible: false,
      // 详情加载状态
      detailLoading: false,
      // 路线详情
      routeDetail: {
        route: {},
        items: []
      }
    }
  },
  created() {
    this.getList()
    this.getLeaderOptions()
  },
  methods: {
    // 获取路线列表
    getList() {
      this.loading = true
      listDeliveryRoutes(this.queryParams).then(response => {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response)) {
          this.routeList = response
          this.total = response.length
        } else {
          // 否则尝试获取list和total字段
          this.routeList = response.list || response.records || []
          this.total = response.total || 0
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取团长选项
    getLeaderOptions() {
      getAvailableLeaders().then(response => {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response)) {
          this.availableLeaders = response
        } else {
          this.availableLeaders = response || []
        }
      })
    },
    // 搜索按钮点击事件
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    // 重置按钮点击事件
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryParams.name = ''
      this.queryParams.status = ''
      this.queryParams.current = 1
      this.getList()
    },
    // 每页数量改变事件
    handleSizeChange(val) {
      this.queryParams.size = val
      this.getList()
    },
    // 页码改变事件
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },
    // 添加按钮点击事件
    handleAdd() {
      this.dialogTitle = '添加配送路线'
      this.form = {
        id: undefined,
        name: '',
        description: '',
        status: 1,
        items: []
      }
      this.dialogVisible = true
    },
    // 编辑按钮点击事件
    handleUpdate(row) {
      this.dialogTitle = '编辑配送路线'
      this.detailLoading = true
      
      getDeliveryRoute(row.id).then(response => {
        const { route, items } = response || { route: {}, items: [] }
        this.form = {
          id: route.id,
          name: route.name,
          description: route.description,
          status: route.status,
          items: items.map(item => ({
            leaderId: item.leaderId
          }))
        }
        this.dialogVisible = true
        this.detailLoading = false
      }).catch(() => {
        this.detailLoading = false
      })
    },
    // 详情按钮点击事件
    handleDetail(row) {
      this.detailVisible = true
      this.detailLoading = true
      this.routeDetail = {
        route: {},
        items: []
      }
      
      getDeliveryRoute(row.id).then(response => {
        this.routeDetail = response || { route: {}, items: [] }
        this.detailLoading = false
      }).catch(() => {
        this.detailLoading = false
      })
    },
    // 删除按钮点击事件
    handleDelete(row) {
      this.$confirm('确认删除该配送路线吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDeliveryRoute(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {})
    },
    // 状态改变事件
    handleStatusChange(row) {
      const text = row.status === 1 ? '启用' : '禁用'
      this.$confirm(`确认${text}该配送路线吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeDeliveryRouteStatus(row.id, row.status).then(() => {
          this.$message.success(`${text}成功`)
        })
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1
      })
    },
    // 添加配送点
    addRouteItem() {
      this.form.items.push({
        leaderId: ''
      })
    },
    // 移除配送点
    removeRouteItem(index) {
      this.form.items.splice(index, 1)
    },
    // 判断团长是否已被选择
    isLeaderSelected(leaderId, currentIndex) {
      return this.form.items.findIndex((item, index) => index !== currentIndex && item.leaderId === leaderId) !== -1
    },
    // 获取团长名称
    getLeaderName(leaderId) {
      const leader = this.availableLeaders.find(item => item.id === leaderId)
      return leader ? leader.name : ''
    },
    // 获取团长地址
    getLeaderAddress(leaderId) {
      const leader = this.availableLeaders.find(item => item.id === leaderId)
      return leader ? leader.address : ''
    },
    // 表单提交事件
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.items.length === 0) {
            this.$message.warning('请至少添加一个配送点')
            return
          }
          
          if (this.form.id) {
            updateDeliveryRoute(this.form).then(() => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            addDeliveryRoute(this.form).then(() => {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.route-items {
  .empty-tip {
    color: #909399;
    text-align: center;
    padding: 20px 0;
    background-color: #f5f7fa;
    border-radius: 4px;
    border: 1px dashed #d9d9d9;
  }
  
  .route-item {
    margin-bottom: 15px;
    
    .route-item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .route-item-info {
      margin-top: 10px;
      
      .leader-info {
        margin-bottom: 5px;
        
        .label {
          color: #606266;
          margin-right: 10px;
        }
      }
    }
  }
  
  .add-item {
    margin-top: 15px;
    text-align: center;
    
    .el-button {
      width: 100%;
      border: 1px dashed #d9d9d9;
    }
  }
}

.route-map {
  margin-top: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  
  .route-map-title {
    font-size: 16px;
    font-weight: bold;
    padding: 15px;
    border-bottom: 1px solid #EBEEF5;
    background-color: #F5F7FA;
  }
  
  .route-map-content {
    padding: 20px;
    
    .route-point {
      display: flex;
      position: relative;
      
      .route-step {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 40px;
        margin-right: 15px;
        
        .point-number {
          width: 36px;
          height: 36px;
          background-color: #409EFF;
          color: #fff;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          font-weight: bold;
          z-index: 2;
        }
        
        .point-line {
          width: 2px;
          height: 100%;
          background-color: #409EFF;
          margin-top: 5px;
          margin-bottom: -15px;
          flex-grow: 1;
          position: absolute;
          top: 36px;
          bottom: 0;
          left: 19px;
          z-index: 1;
        }
      }
      
      .point-card {
        flex: 1;
        border: 1px solid #EBEEF5;
        border-radius: 4px;
        margin-bottom: 20px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        
        .point-header {
          padding: 10px 15px;
          font-weight: bold;
          border-bottom: 1px solid #EBEEF5;
          background-color: #F5F7FA;
        }
        
        .point-body {
          padding: 15px;
          
          .point-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            
            i {
              color: #409EFF;
              margin-right: 10px;
              font-size: 16px;
            }
            
            &:last-child {
              margin-bottom: 0;
            }
          }
        }
      }
      
      &:last-child {
        .point-card {
          margin-bottom: 0;
        }
      }
    }
  }
}
</style> 